<?php

namespace app\ask\controller;

use think\Controller;

class Sign extends Controller
{
    protected $SignModel;
    protected $BusinessModel;

    public function __construct()
    {
        parent::__construct();

        $this->SignModel = model('Sign');
        $this->BusinessModel = model('Business.Business');
    }

    // 签到列表
    public function index()
    {
        $busid = $this->request->param('busid', 0, 'intval');
        $year = $this->request->param('year', 2022, 'intval');
        $month = $this->request->param('month', 1, 'intval');

        if ($month < 1 || $month > 12) {
            $this->error('月份错误');
            exit;
        }

        // 计算当月的天数
        $daysInMonth = date("t", strtotime("$year-$month"));

        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->error('用户不存在');
            exit;
        }

        $list = $this->SignModel
            ->where('createtime', 'between time', ["$year-$month-1", "$year-$month-$daysInMonth"])
            ->where(['busid' => $busid])
            ->select();

        if (empty($list)) {
            $list = [];
        }

        $this->success('ok', '', $list);
    }

    // 签到
    public function sign()
    {
        $busid = $this->request->param('busid', 0, 'intval');

        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->error('用户不存在');
            exit;
        }

        $currentDate = date("Y-m-d");

        $sign = $this->SignModel
            ->where('createtime', 'between time', ["$currentDate 00:00:00", "$currentDate 23:59:59"])
            ->where(['busid' => $busid])
            ->find();

        if ($sign) {
            $this->error('今天已经签到过了');
            exit;
        }

        $point = 1;

        $data = [
            'busid' => $busid,
            'point' => $point,
        ];

        $this->SignModel->startTrans();
        $this->BusinessModel->startTrans();

        $signRes = $this->SignModel->save($data);

        if ($signRes === false) {
            $this->error($this->SignModel->getError());
            exit;
        }

        $businessData = [
            'id' => $busid,
            'point' => bcadd($business['point'], $point),
        ];

        $businessRes = $this->BusinessModel->isUpdate(true)->save($businessData);

        if($businessRes === false){
            $this->SignModel->rollback();
            $this->error($this->BusinessModel->getError());
            exit;
        }

        if ($signRes === false || $businessRes === false) {
            $this->SignModel->rollback();
            $this->BusinessModel->rollback();
            $this->error('签到失败');
            exit;
        } else {
            $this->BusinessModel->commit();
            $this->SignModel->commit();
            $this->success("签到成功 获得 $point 积分");
            exit;
        }
    }
}
